package net.csdra.DongPoShuZiTuShuGuan.util;

import net.csdra.DongPoShuZiTuShuGuan.domain.EntityBase;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * Created by add on 2018/1/17.
 */
public class Utils {

    public static void copy(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

    /**
     * 返回所有为空属性的名称
     *
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            System.out.println(srcValue);
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static <T extends EntityBase> T createAutoSet(Class<T> tClass, String currentUserName) {
        T t = null;
        try {
            t = tClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        currentUserName = StringUtils.hasText(currentUserName) ? currentUserName : "system";
        String id = UUID.randomUUID().toString();
        String createBy = currentUserName;
        Timestamp createTime = new Timestamp(new Date().getTime());
        String lastModifiedBy = currentUserName;
        Timestamp lastModifiedTime = new Timestamp(new Date().getTime());
        Long order = 0L;
        t.setId(id);
        t.setCreateBy(createBy);
        t.setCreateTime(createTime);
        t.setLastModifiedBy(lastModifiedBy);
        t.setLastModifiedTime(lastModifiedTime);
        t.setDeleted(false);
        t.setEnabled(true);
        t.setOrder(order);
        return t;
    }

    public static boolean isNumeric(String str){
        for(int i=str.length();--i>=0;){
            int chr=str.charAt(i);
            if(chr<48 || chr>57)
                return false;
        }
        return true;
    }
}
